<template>
  <PageContainer
    title="收货开票"
    :actions="pageActions"
    :columns="columns"
    :data-source="orderList"
    :loading="loading"
    :table-scroll="tableScroll"
    :pagination-data="pagination"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 筛选条件 -->
    <template #filter-items>
      <!-- 只有超级管理员在全部站点模式下才显示发货站点筛选器 -->

      <a-form-item label="运单编号">
        <a-input
          v-model:value="queryParams.orderNo"
          placeholder="输入运单编号"
          allowClear
        />
      </a-form-item>

      <a-form-item label="货物编码">
        <a-input
          v-model:value="queryParams.goodsCode"
          placeholder="输入货物编码"
          allowClear
        />
      </a-form-item>

      <a-form-item
        v-if="
          userStore.userInfo?.role === 'SUPER_ADMIN' &&
          userStore.userInfo?.siteId === null
        "
        label="发货站点"
      >
        <a-select
          v-model:value="queryParams.departureSiteId"
          placeholder="全部发货站点"
          allowClear
          :loading="siteLoading"
        >
          <a-select-option
            v-for="site in siteOptions"
            :key="site.id"
            :value="site.id"
          >
            {{ site.siteName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="到货站点">
        <a-select
          v-model:value="queryParams.arrivalSiteId"
          placeholder="全部到货站点"
          allowClear
          :loading="siteLoading"
        >
          <a-select-option
            v-for="site in siteOptions"
            :key="`arrival-${site.id}`"
            :value="site.id"
            :disabled="site.id === userStore.userInfo?.siteId"
          >
            {{ site.siteName }}
            <span
              v-if="site.id === userStore.userInfo?.siteId"
              style="color: #999; font-size: 12px"
            >
              （当前站点）
            </span>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="收货司机">
        <a-select
          v-model:value="queryParams.driverId"
          placeholder="输入司机姓名/工号搜索"
          allowClear
          show-search
          :filter-option="false"
          :loading="driverLoading"
          @search="handleDriverSearch"
          @focus="handleDriverFocus"
        >
          <a-select-option
            v-for="driver in driverOptions"
            :key="driver.id"
            :value="driver.id"
          >
            {{ driver.name }}（{{ driver.driverNo }}）
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="运输车辆">
        <a-select
          v-model:value="queryParams.vehicleId"
          placeholder="输入车牌号搜索"
          allowClear
          show-search
          :filter-option="false"
          :loading="vehicleLoading"
          @search="handleVehicleSearch"
          @focus="handleVehicleFocus"
        >
          <a-select-option
            v-for="vehicle in vehicleOptions"
            :key="vehicle.id"
            :value="vehicle.id"
          >
            {{ vehicle.plateNumber }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="付款方式">
        <a-select
          v-model:value="queryParams.paymentMethod"
          placeholder="全部付款方式"
          allowClear
          :options="paymentMethodOptions"
        />
      </a-form-item>

      <a-form-item label="订单状态">
        <a-select
          v-model:value="queryParams.orderStatus"
          placeholder="全部状态"
          allowClear
          :options="statusOptions"
        />
      </a-form-item>

      <a-form-item label="时间范围" class="col-span-2">
        <a-range-picker
          v-model:value="dateRange"
          format="YYYY-MM-DD"
          :placeholder="['开始日期', '结束日期']"
        />
      </a-form-item>

      <a-form-item label="发货人">
        <a-input
          v-model:value="queryParams.senderName"
          placeholder="输入发货人姓名"
          allowClear
        />
      </a-form-item>

      <a-form-item label="发货电话">
        <a-input
          v-model:value="queryParams.senderPhone"
          placeholder="输入发货电话"
          allowClear
        />
      </a-form-item>

      <a-form-item label="收货人">
        <a-input
          v-model:value="queryParams.receiverName"
          placeholder="输入收货人姓名"
          allowClear
        />
      </a-form-item>

      <a-form-item label="收货电话">
        <a-input
          v-model:value="queryParams.receiverPhone"
          placeholder="输入收货电话"
          allowClear
        />
      </a-form-item>

      <a-form-item label="货物名称">
        <a-input
          v-model:value="queryParams.goodsName"
          placeholder="输入货物名称"
          allowClear
        />
      </a-form-item>

      <a-form-item label="开票员">
        <a-input
          v-model:value="queryParams.issuerName"
          placeholder="输入开票员姓名"
          allowClear
        />
      </a-form-item>

      <a-form-item label="关键字">
        <a-input
          v-model:value="queryParams.keyword"
          placeholder="姓名/电话/单号等关键字"
          allowClear
        />
      </a-form-item>
    </template>

    <!-- 表格内容 -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'orderInfo'">
        <div class="order-info">
          <a class="order-no-link" @click="handleView(record)">{{
            record.orderNo
          }}</a>
          <div class="order-meta">编码：{{ record.goodsCode || "未填写" }}</div>
        </div>
      </template>

      <template v-else-if="column.key === 'sites'">
        <div class="site-route">
          <span>{{ record.departureSiteName || "未填写" }}</span>
          <ArrowRightOutlined class="site-arrow" />
          <span>{{ record.arrivalSiteName || "未填写" }}</span>
        </div>
      </template>

      <template v-else-if="column.key === 'receiver'">
        <div class="contact-block">
          <span class="contact-name">{{ record.receiverName || "-" }}</span>
          <span class="contact-phone">{{ record.receiverPhone || "-" }}</span>
        </div>
      </template>

      <template v-else-if="column.key === 'sender'">
        <div class="contact-block">
          <span class="contact-name">{{ record.senderName || "-" }}</span>
          <span class="contact-phone">{{ record.senderPhone || "-" }}</span>
        </div>
      </template>

      <template v-else-if="column.key === 'goods'">
        <div class="goods-info">
          <span class="goods-name">{{ record.goodsName || "-" }}</span>
          <span class="goods-detail"
            >{{ record.goodsPackage || "未填写" }} ·
            {{ record.goodsPieces || 0 }}件</span
          >
        </div>
      </template>

      <template v-else-if="column.key === 'deliveryInfo'">
        <div class="delivery-info">
          <div>
            {{ record.deliveryType === "PICKUP" ? "到站自提" : "送货上门" }}
          </div>
          <div
            v-if="record.deliveryOptions"
            style="
              margin-top: 4px;
              font-size: 12px;
              color: var(--primary-color);
            "
          >
            <template
              v-for="(opt, idx) in record.deliveryOptions.split(',')"
              :key="opt"
            >
              <span v-if="idx > 0"> · </span>
              <span v-if="opt === 'SIGN_RECEIPT'">签回单</span>
              <span v-else-if="opt === 'PRINT_RECEIPT'">打收条</span>
            </template>
          </div>
        </div>
      </template>

      <template v-else-if="column.key === 'driver'">
        <div v-if="record.driverName || record.driverPhone" class="driver-info">
          <div class="driver-name">{{ record.driverName || "-" }}</div>
          <div v-if="record.driverPhone" class="driver-phone">
            {{ record.driverPhone }}
          </div>
        </div>
        <span v-else class="text-secondary">未分配</span>
      </template>

      <template v-else-if="column.key === 'vehicle'">
        <div v-if="record.vehiclePlate" class="vehicle-info">
          <div class="vehicle-plate">{{ record.vehiclePlate }}</div>
        </div>
        <span v-else class="text-secondary">-</span>
      </template>

      <template v-else-if="column.key === 'freightAmount'">
        <span class="freight-amount">{{
          formatMoney(record.freightAmount)
        }}</span>
      </template>

      <template v-else-if="column.key === 'settlementAmount'">
        <span class="settlement-amount">{{
          formatMoney(record.settlementAmount)
        }}</span>
      </template>

      <template v-else-if="column.key === 'paymentMethod'">
        <span>{{
          record.paymentMethod
            ? getPaymentMethodLabel(record.paymentMethod)
            : "未选择"
        }}</span>
      </template>

      <template v-else-if="column.key === 'collectionAmount'">
        <span>{{ formatMoney(record.collectionAmount) }}</span>
      </template>

      <template v-else-if="column.key === 'issuer'">
        <span>{{ record.issuerName || "-" }}</span>
      </template>

      <template v-else-if="column.key === 'dispatchTime'">
        <span>{{
          record.dispatchTime ? formatDateTime(record.dispatchTime) : "-"
        }}</span>
      </template>

      <template v-else-if="column.key === 'arrivalTime'">
        <span>{{
          record.arrivalTime ? formatDateTime(record.arrivalTime) : "-"
        }}</span>
      </template>

      <template v-else-if="column.key === 'createTime'">
        {{ formatDateTime(record.createTime) }}
      </template>

      <template v-else-if="column.key === 'orderStatus'">
        <a-tag :color="getStatusMeta(record.orderStatus)?.color">
          {{ getStatusMeta(record.orderStatus)?.label || record.orderStatus }}
        </a-tag>
      </template>

      <template v-else-if="column.key === 'remark'">
        <a-tooltip :title="record.remark || ''">
          <span class="text-ellipsis">{{ record.remark || "-" }}</span>
        </a-tooltip>
      </template>

      <template v-else-if="column.key === 'action'">
        <a-space>
          <a-button type="link" size="small" @click="handleView(record)">
            查看
          </a-button>
          <a-button
            type="link"
            size="small"
            @click="handleEdit(record)"
            v-permission="($route?.meta as any)?.$actions?.['edit']?.code"
          >
            编辑
          </a-button>
          <a-button
            v-if="record.orderStatus === 'RECEIVED'"
            type="link"
            size="small"
            @click="handleAssign(record)"
            v-permission="($route?.meta as any)?.$actions?.['assign']?.code"
          >
            {{ record.driverId ? "修改司机" : "分配司机" }}
          </a-button>
          <a-button
            v-if="record.orderStatus !== 'CANCELLED'"
            type="link"
            size="small"
            danger
            @click="handleCancel(record)"
          >
            取消
          </a-button>
          <a-button
            v-if="record.orderStatus === 'CANCELLED'"
            type="link"
            size="small"
            danger
            @click="handleDelete(record)"
            v-permission="($route?.meta as any)?.$actions?.['delete']?.code"
          >
            删除
          </a-button>
        </a-space>
      </template>
    </template>
  </PageContainer>

  <!-- 取消订单弹窗 -->
  <a-modal
    v-model:open="showCancelModal"
    title="取消收货开票"
    @ok="confirmCancel"
    @cancel="showCancelModal = false"
  >
    <p class="cancel-tip">
      确定要取消运单 <strong>{{ currentCancelOrder?.orderNo }}</strong> 吗？
    </p>

    <a-form-item label="取消原因">
      <a-select v-model:value="cancelReason" style="width: 100%">
        <a-select-option value="客户取消">客户取消</a-select-option>
        <a-select-option value="货物问题">货物问题</a-select-option>
        <a-select-option value="无法配送">无法配送</a-select-option>
        <a-select-option value="其他原因">其他原因</a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item label="详细说明">
      <a-textarea
        v-model:value="cancelDetail"
        placeholder="请填写详细说明（必填）"
        :rows="4"
        :maxlength="500"
        show-count
      />
    </a-form-item>
  </a-modal>

  <!-- 分配司机弹窗 -->
  <a-modal
    v-model:open="showAssignModal"
    title="分配司机"
    @ok="confirmAssign"
    @cancel="showAssignModal = false"
    :width="500"
  >
    <a-form :model="assignForm" layout="vertical">
      <a-form-item label="选择司机" required>
        <a-select
          v-model:value="assignForm.driverId"
          placeholder="请选择司机"
          :loading="assignDriverLoading"
          show-search
          :filter-option="filterAssignDriverOption"
        >
          <a-select-option
            v-for="driver in availableDrivers"
            :key="driver.id"
            :value="driver.id"
            :disabled="
              driver.driverStatus !== 'IDLE' &&
              driver.id !== currentAssignOrder?.driverId
            "
          >
            {{ driver.name }}（{{ driver.driverNo }}） - {{ driver.phone }}
            <span
              v-if="
                driver.driverStatus !== 'IDLE' &&
                driver.id !== currentAssignOrder?.driverId
              "
              style="color: #999"
            >
              （{{ getDriverStatusLabel(driver.driverStatus) }}）
            </span>
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import {
  PlusOutlined,
  ExportOutlined,
  ArrowRightOutlined,
} from "@ant-design/icons-vue";
import PageContainer from "@/components/business/PageContainer.vue";
import {
  getOrderList,
  cancelOrder,
  deleteOrder,
  assignOrder,
} from "@/api/tenant/order";
import { getDriverList } from "@/api/tenant/driver";
import { getSiteList } from "@/api/tenant/site";
import { getVehicleList } from "@/api/tenant/vehicle";
import { getInvoicerUsers } from "@/api/tenant/user";
import { useDictionary } from "@/composables/useDictionary";
import { useUserStore } from "@/stores/user";
import type {
  Order,
  OrderQueryParams,
  OrderStatus,
  OrderAssignRequest,
} from "@/types/order";
import { ORDER_STATUS_CONFIG } from "@/types/order";
import type { Site } from "@/types/site";
import type { Driver } from "@/types/driver";
import type { Vehicle } from "@/types/vehicle";
import { formatDateTime, formatMoney } from "@/utils/format";
import type { Dayjs } from "dayjs";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const dateRange = ref<[Dayjs, Dayjs] | null>(null);

const queryParams = reactive<OrderQueryParams>({
  current: 1,
  size: 10,
  orderStatus: undefined,
  orderNo: "",
  goodsCode: "",
  departureSiteId: undefined,
  arrivalSiteId: undefined,
  driverId: undefined,
  vehicleId: undefined,
  paymentMethod: undefined,
  keyword: "",
  senderName: "",
  receiverName: "",
  senderPhone: "",
  receiverPhone: "",
  driverName: "",
  driverPhone: "",
  goodsName: "",
  issuerName: "",
});

const orderList = ref<Order[]>([]);
const loading = ref(false);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ["10", "20", "50", "100"],
});

// 页面操作按钮配置
const pageActions = computed(() => [
  {
    key: "create",
    label: "新增开票",
    type: "primary" as const,
    icon: PlusOutlined,
    permission: (route.meta as any)?.$actions?.create?.code,
    onClick: handleCreate,
  },
  {
    key: "export",
    label: "导出",
    icon: ExportOutlined,
    onClick: () => {
      message.info("导出功能开发中");
    },
  },
]);

const columns = [
  {
    title: "运单信息",
    key: "orderInfo",
    fixed: "left" as const,
    width: 200,
  },
  {
    title: "站点路线",
    key: "sites",
    width: 220,
  },
  {
    title: "收货人/电话",
    key: "receiver",
    width: 120,
  },
  {
    title: "发货人/电话",
    key: "sender",
    width: 120,
  },
  {
    title: "货物信息",
    key: "goods",
    width: 120,
  },
  {
    title: "配送方式",
    key: "deliveryInfo",
    width: 140,
  },
  {
    title: "运输车辆",
    key: "vehicle",
    width: 120,
  },
  {
    title: "实收运费",
    key: "freightAmount",
    width: 100,
  },
  {
    title: "结算运费",
    key: "settlementAmount",
    width: 100,
  },
  {
    title: "付款方式",
    key: "paymentMethod",
    width: 100,
  },
  {
    title: "代收款",
    dataIndex: "collectionAmount",
    key: "collectionAmount",
    width: 100,
  },
  {
    title: "状态",
    dataIndex: "orderStatus",
    key: "orderStatus",
    width: 100,
    align: "center" as const,
  },
  {
    title: "收货司机",
    key: "driver",
    width: 140,
  },
  {
    title: "发车时间",
    key: "dispatchTime",
    width: 180,
  },
  {
    title: "到货时间",
    key: "arrivalTime",
    width: 180,
  },
  {
    title: "开票员",
    key: "issuer",
    width: 100,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    width: 180,
  },
  {
    title: "备注",
    key: "remark",
    width: 200,
  },
  {
    title: "操作",
    key: "action",
    fixed: "right" as const,
    width: 250,
    align: "center" as const,
  },
];

// 根据列宽动态计算横向滚动宽度，避免表头/表体不同步
const tableScrollX = computed(() =>
  columns.reduce(
    (sum, col: any) => sum + (col.width ? Number(col.width) : 0),
    0
  )
);

const tableScroll = computed(() => ({
  x: tableScrollX.value,
  // y 由 flex 布局自动控制，不需要固定高度
}));

const siteOptions = ref<Site[]>([]);
const siteLoading = ref(false);
const driverOptions = ref<Driver[]>([]);
const driverLoading = ref(false);
const vehicleOptions = ref<Vehicle[]>([]);
const vehicleLoading = ref(false);
const invoicerOptions = ref<{ label: string; value: number }[]>([]);

// 加载开票员用户列表
const loadInvoicers = async () => {
  try {
    const response = await getInvoicerUsers();
    const users = response.data as any;
    invoicerOptions.value = (users || []).map((user: any) => ({
      label: user.realName,
      value: user.id,
    }));
  } catch (error) {
    console.error("获取开票员列表失败", error);
  }
};

const loadSites = async () => {
  siteLoading.value = true;
  try {
    const siteResponse = await getSiteList();
    siteOptions.value = (siteResponse.data as any) ?? [];
  } catch (error) {
    console.error("获取站点列表失败", error);
  } finally {
    siteLoading.value = false;
  }
};

// 搜索司机（远程搜索，支持关键词）
let driverSearchTimer: any = null;
const searchDrivers = async (keyword: string = "") => {
  driverLoading.value = true;
  try {
    const response = await getDriverList({
      current: 1,
      size: 50, // 限制返回数量
      siteId: userStore.userInfo?.siteId ?? undefined,
      keyword: keyword.trim(),
    });
    const data = response.data as any;
    driverOptions.value = data.records || [];
  } catch (error) {
    console.error("获取司机列表失败", error);
  } finally {
    driverLoading.value = false;
  }
};

// 司机搜索处理（防抖）
const handleDriverSearch = (value: string) => {
  if (driverSearchTimer) clearTimeout(driverSearchTimer);
  driverSearchTimer = setTimeout(() => {
    searchDrivers(value);
  }, 300);
};

// 司机下拉框获得焦点时加载数据
const handleDriverFocus = () => {
  if (driverOptions.value.length === 0) {
    searchDrivers();
  }
};

// 搜索车辆（远程搜索，支持车牌号）
let vehicleSearchTimer: any = null;
const searchVehicles = async (keyword: string = "") => {
  vehicleLoading.value = true;
  try {
    const response = await getVehicleList({
      current: 1,
      size: 50, // 限制返回数量
      keyword: keyword.trim(),
    });
    const data = response.data as any;
    vehicleOptions.value = data.records || [];
  } catch (error) {
    console.error("获取车辆列表失败", error);
  } finally {
    vehicleLoading.value = false;
  }
};

// 车辆搜索处理（防抖）
const handleVehicleSearch = (value: string) => {
  if (vehicleSearchTimer) clearTimeout(vehicleSearchTimer);
  vehicleSearchTimer = setTimeout(() => {
    searchVehicles(value);
  }, 300);
};

// 车辆下拉框获得焦点时加载数据
const handleVehicleFocus = () => {
  if (vehicleOptions.value.length === 0) {
    searchVehicles();
  }
};

const statusOptions = Object.entries(ORDER_STATUS_CONFIG).map(
  ([value, meta]) => ({
    label: meta.label,
    value: value as OrderStatus,
  })
);

// 使用缓存，但包括已禁用的字典项
// 这样历史订单能正确显示已删除的支付方式标签
const {
  options: paymentMethodOptions,
  loadDictionaries: loadPaymentMethods,
  getLabel: getPaymentMethodLabel,
} = useDictionary("PAYMENT_METHOD", true, true);

const getStatusMeta = (status?: OrderStatus) => {
  if (!status) return undefined;
  return ORDER_STATUS_CONFIG[status];
};

const fetchOrderList = async () => {
  loading.value = true;
  try {
    const currentSiteId = userStore.userInfo?.siteId;

    const params: Record<string, any> = {
      ...queryParams,
      current: pagination.current,
      size: pagination.pageSize,
    };

    // 收货开票页面：如果选择了具体站点，只显示该站点的发货订单；如果选择全部站点，显示所有订单
    if (currentSiteId) {
      params.departureSiteId = currentSiteId;
    }

    if (dateRange.value && dateRange.value.length === 2) {
      params.startTime = dateRange.value[0].format("YYYY-MM-DD 00:00:00");
      params.endTime = dateRange.value[1].format("YYYY-MM-DD 23:59:59");
    }

    const orderResponse = await getOrderList(params);
    const orderData = orderResponse.data as any;
    orderList.value = orderData?.records ?? [];
    pagination.total = orderData?.total ?? 0;
  } catch (error) {
    console.error("获取收货开票列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchOrderList();
};

const handleReset = () => {
  Object.assign(queryParams, {
    orderStatus: undefined,
    orderNo: "",
    goodsCode: "",
    departureSiteId: undefined,
    arrivalSiteId: undefined,
    driverId: undefined,
    vehicleId: undefined,
    paymentMethod: undefined,
    keyword: "",
    senderName: "",
    receiverName: "",
    senderPhone: "",
    receiverPhone: "",
    driverName: "",
    driverPhone: "",
    goodsName: "",
    issuerName: "",
  });
  dateRange.value = null;
  // 重置时清空司机和车辆下拉选项
  driverOptions.value = [];
  vehicleOptions.value = [];
  pagination.current = 1;
  fetchOrderList();
};

const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchOrderList();
};

const handleCreate = () => {
  router.push("/tenant/order/create");
};

const handleView = (record: Order) => {
  router.push(`/tenant/order/${record.id}`);
};

const handleEdit = (record: Order) => {
  router.push(`/tenant/order/edit/${record.id}`);
};

const currentCancelOrder = ref<Order | null>(null);
const showCancelModal = ref(false);
const cancelReason = ref("客户取消");
const cancelDetail = ref("");

const handleCancel = (record: Order) => {
  currentCancelOrder.value = record;
  showCancelModal.value = true;
  cancelReason.value = "客户取消";
  cancelDetail.value = "";
};

const confirmCancel = async () => {
  if (!cancelDetail.value) {
    message.warning("请填写详细说明");
    return;
  }

  if (!currentCancelOrder.value) return;

  try {
    await cancelOrder(currentCancelOrder.value.id, {
      cancelReason: cancelReason.value,
      detail: cancelDetail.value,
    });
    message.success("开票已取消");
    showCancelModal.value = false;
    fetchOrderList();
  } catch (error: any) {
    console.error("取消开票失败:", error);
    if (error?.message && error.message !== "Error") {
      message.error(error.message);
    }
  }
};

const handleDelete = (record: Order) => {
  import("ant-design-vue").then(({ Modal, message: msg }) => {
    Modal.confirm({
      title: "删除收货开票",
      content: `确定要删除运单 ${record.orderNo} 吗？删除后无法恢复。`,
      okText: "确定删除",
      okType: "danger",
      cancelText: "取消",
      onOk: async () => {
        try {
          await deleteOrder(record.id);
          msg.success("删除成功");
          fetchOrderList();
        } catch (error: any) {
          console.error("删除收货开票失败:", error);
          if (error?.message && error.message !== "Error") {
            msg.error(error.message);
          }
        }
      },
    });
  });
};

// 分配司机相关
const showAssignModal = ref(false);
const currentAssignOrder = ref<Order | null>(null);
const availableDrivers = ref<Driver[]>([]);
const assignDriverLoading = ref(false);
const assignForm = reactive<OrderAssignRequest>({
  driverId: undefined as any,
});

// 司机状态字典
const { getLabel: getDriverStatusLabel, loadDictionaries: loadDriverStatuses } =
  useDictionary("DRIVER_STATUS");

// 获取当前站点的司机列表
const fetchAvailableDrivers = async () => {
  assignDriverLoading.value = true;
  try {
    const currentSiteId = userStore.userInfo?.siteId;

    const response = await getDriverList({
      current: 1,
      size: 100,
      siteId: currentSiteId ?? undefined, // 只获取当前站点的司机
    });
    const data = response.data as any;
    // 显示所有司机，但在下拉框中根据状态禁用
    availableDrivers.value = data.records || [];
  } catch (error) {
    console.error("获取司机列表失败:", error);
    message.error("获取司机列表失败");
  } finally {
    assignDriverLoading.value = false;
  }
};

// 司机搜索过滤（分配司机modal用）
const filterAssignDriverOption = (input: string, option: any) => {
  const driver = availableDrivers.value.find((d) => d.id === option.value);
  if (!driver) return false;
  return (
    driver.name.toLowerCase().includes(input.toLowerCase()) ||
    driver.driverNo.toLowerCase().includes(input.toLowerCase()) ||
    driver.phone.includes(input)
  );
};

// 打开分配对话框
const handleAssign = (record: Order) => {
  currentAssignOrder.value = record;
  assignForm.driverId = record.driverId || (undefined as any);
  showAssignModal.value = true;
  fetchAvailableDrivers();
};

// 确认分配
const confirmAssign = async () => {
  if (!assignForm.driverId) {
    message.warning("请选择司机");
    return;
  }

  if (!currentAssignOrder.value) return;

  try {
    await assignOrder(currentAssignOrder.value.id, {
      driverId: assignForm.driverId,
    });
    message.success("司机分配成功");
    showAssignModal.value = false;
    fetchOrderList();
  } catch (error: any) {
    console.error("分配司机失败:", error);
    if (error?.message && error.message !== "Error") {
      message.error(error.message);
    }
  }
};

onMounted(async () => {
  // 从路由 state 初始化筛选条件（用于从司机/车辆页面跳转过来）
  // 只有明确标记 fromNavigation 时才应用筛选，刷新页面时不应用
  const state = window.history.state;

  if (state?.fromNavigation) {
    // 应用筛选条件
    if (state.driverId) {
      queryParams.driverId = Number(state.driverId);
      // 如果有司机ID参数，预加载司机列表（包含该司机）
      await searchDrivers();
    }
    if (state.vehicleId) {
      queryParams.vehicleId = Number(state.vehicleId);
      // 如果有车辆ID参数，预加载车辆列表（包含该车辆）
      await searchVehicles();
    }

    // 应用后立即清除标记，防止刷新时重复应用
    window.history.replaceState({ ...state, fromNavigation: false }, "");
  }

  await Promise.all([
    loadSites(),
    loadPaymentMethods(),
    loadDriverStatuses(),
    loadInvoicers(), // 加载开票员列表
  ]);
  fetchOrderList();
});
</script>

<style scoped>
/* 表格内容样式 */

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-no-link {
  font-weight: 600;
  color: var(--primary-color);
}

.order-meta {
  font-size: 12px;
  color: var(--text-secondary);
}

.site-route {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-primary);
}

.site-arrow {
  color: var(--text-secondary);
}

.contact-block {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.contact-name {
  font-weight: 500;
}

.contact-phone {
  font-size: 12px;
  color: var(--text-secondary);
}

.goods-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.goods-name {
  font-weight: 500;
}

.goods-detail {
  font-size: 12px;
  color: var(--text-secondary);
}

.vehicle-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.vehicle-plate {
  font-size: 12px;
  color: var(--text-secondary);
}

.freight-amount {
  font-weight: 600;
  color: var(--success-color);
}

.settlement-amount {
  font-weight: 600;
  color: var(--primary-color);
}

.text-secondary {
  color: var(--text-secondary);
}

.text-ellipsis {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 取消弹窗样式 */
.cancel-tip {
  margin-bottom: 16px;
}
</style>
